﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MesTool
{
    public class HttpHelper
    {
        public static async Task<string> PostAsyncJson(string url, string json)
        {
            HttpClient client = new HttpClient();
            HttpContent content = new StringContent(json);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpResponseMessage response = await client.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }
        public static string Post(string url, string jsonData,IPAddress ipaddress = null)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            if (ipaddress != null)
            {
                request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint((a, b, c) => new IPEndPoint(ipaddress, 0));
            }
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.KeepAlive = true;
            try
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(jsonData);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();

                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                string responseContent = streamReader.ReadToEnd();
                httpWebResponse.Close();
                streamReader.Close();
                return responseContent;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <param name="urlstr"></param>
        /// <returns></returns>
        public static string Get(string urlstr)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    //get
                    var url = new Uri(urlstr);
                    // response
                    var response = httpClient.GetAsync(url).Result;
                    var data = response.Content.ReadAsStringAsync().Result;
                    return data;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
}
